<?php


namespace app\admin\business;

use app\common\model\mysql\AdminUser as AdminUserModel;
use think\Exception;

class AdminUser
{
    public static function login($data){
        try {
            $adminUserObj = new AdminUserModel();
            $adminUser = self::getAdminUserByUsername($data['username']);
            if(empty($adminUser)){
                throw new Exception("不存在该用户");
            }
            if($adminUser['password'] != md5($data['password']."_tianQi_abc")){
                throw new Exception("密码不正确");
                //return show(config("status.error"), "密码不正确");
            }
            // 记录登录信息到mysql中
            $updateData = [
                "last_login_ip" => request()->ip(),
                "last_login_time" => date("Y-m-d H:i:s",time()),
                "update_time" => date("Y-m-d H:i:s",time())
            ];
            $res = $adminUserObj->updateById($adminUser['id'], $updateData);
            if(empty($res)) {
                throw new Exception("登录失败");
                //return show(config("status.error"), "登录失败");
            }
        } catch (\Exception $e){
            //todo 记录日志 $e->getMessage();
            throw new Exception("内部异常，登录失败");
            //return show(config("status.error"), "内部异常，登录失败");
        }
        // 记录Session
        session(config('admin.session_admin'), $adminUser);
        return true;
    }

    /**
     * 通过用户名获取用户数据
     * @param $username
     * @return false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAdminUserByUsername($username){
        $adminUserObj = new AdminUserModel();
        $adminUser = $adminUserObj->getAdminUserByUsername($username);
        // halt($adminUser);
        if(empty($adminUser) || $adminUser->status != config('status.mysql.table_normal')){
            return false;
        }
        $adminUser = $adminUser->toArray();
        return $adminUser;
    }
}